/*
 * @Date: 2023-03-22 16:35:49
 * @LastEditors: Chuying
 * @LastEditTime: 2023-04-03 13:59:45
 * @Description:
 */
import {
  Controller,
  Get,
  Post,
  UseInterceptors,
  UploadedFile,
  Res,
  Param,
  StreamableFile,
} from '@nestjs/common';
import { FileService } from './file.service';

import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
import { createReadStream } from 'fs';
import type { Response } from 'express';

// import { zip } from 'compressing';

@Controller('file')
export class FileController {
  constructor(private readonly fileService: FileService) {}

  // FileInterceptor是单个 读取字段名称  FilesInterceptor是多个
  // 参数使用UploadedFile 装饰器接受file 文件

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file) {
    console.log(file);
    return { path: `/static/images/${file.filename}` };
  }

  @Get('download/:fileName')
  download(@Param('fileName') fileName: string, @Res() res: Response) {
    const url = join(process.cwd(), `/public/images/${fileName}`);
    console.log(url);
    res.download(url);
  }

  @Get('stream/:fileName')
  down(@Param('fileName') fileName: string, @Res() res: Response) {
    const url = join(process.cwd(), `/public/images/${fileName}`);
    const file = createReadStream(url);
    // res.setHeader('Content-Type', 'application/octet-stream');
    // res.setHeader('Content-Disposition', `attachment; filename=cy`);
    res.set({
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': `attachment; filename=${fileName}`,
    });

    file.pipe(res);
  }
}
